<?php

class ElectionController extends App_Controller_Action
{
		
    public function init()
    {
        /* Initialize action controller here */
    }

    // running elections screen
    public function indexAction()
    {
    	$w = new Winners();
    	$id_winner = $w->getLastWinner();
    	$last_winner = Doctrine::getTable("Projects")->find($id_winner);
		// donation to the view
		$this->view->last_winner = $last_winner;
    }
    
    // vote screen
    public function voteAction()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
    	// check if the user made at least one donation  
		$donation = Doctrine::getTable("Donations")->findOneById_user($this->getUserId());
		
		if (!$donation) {
			// redirect to Donate Screen
			$this->_redirector->gotoSimple("donate", "donation");
			return;
		}
		
		// donation to the view
		$this->view->donation = $donation;
    }
    
	// run election algorithm
    public function runAction()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
    	
        // open log file
		$writer = new Zend_Log_Writer_Stream ( ROOT_PATH.'/tmp/election.log' );
		$logger = new Zend_Log ( $writer );

		// disabled the layout and view
		$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        // load election config values
        $filepath = APPLICATION_PATH . '/configs/election.ini';       
        $config = new Zend_Config_Ini($filepath, null,                              
		    		array(
		    			'skipExtends'        => true,                                    
		    			'allowModifications' => true
		    		)
		);    
        
		// check if the election can run
        $now = new Zend_Date();
		
        // check security keys
		$public_key = $this->_getParam('public_key', '');    	
		$private_key = $this->_getParam('private_key', '');    	
		if ($public_key != $config->keys->public || $private_key != $config->keys->private) {
			// save log
			$logger->info ( 'election not run: wrong key values' );
			return;
		}
		
        // election date
        $election_date = new Zend_Date( );
		$election_date->set ( $config->election->last_election, 'yyyy-MM-dd' );
		$election_date->addDay($config->election->frecuency);
		$election_date->set ( $config->election->time, Zend_Date::TIME_SHORT );
		$time_diff = intval($election_date->toString ( 'HHmm' )) - intval($now->toString ( 'HHmm' ));
		// compare dates 
		if (!$election_date->isToday() || (abs($time_diff) > $config->election->margin)) {
			// save log
			$logger->info ( 'election not run: wrong date and time' );
			return;
		}
		
		// save the last election date on the config file
		$config->election->last_election = $now->toString ( 'yyyy-MM-dd' );
    	$writer = new Zend_Config_Writer_Ini(
    			array(
    				'config'   => $config, 
    				'filename' => $filepath
    			)
    	);
    	$writer->write();        
		
		// count all votes	        
		$votes = new Votes();
		$num_votes = $votes->countAllVotes();

		// count all user allow to vote	        
		$users = new Users();
		$num_users = $users->countAllUsers();
    	
		//  at least 2/3 of the community members must have voted in any given week
		// If less users have voted, the election is voided and no winner is chosen.
		if ($num_votes < intval($num_users*0.65)) {
			// save log
			$logger->info ( 'election run: voided' );
			// save an empty project to the winner list
			$winner = new Winners();
			$winner->day = new Doctrine_Expression("NOW()");							
			$winner->votes = 0;
			$winner->funds = 0;
			$winner->id_project = 1;
	    	$winner->save();
	    	$winner->refresh();
			return;
		}
		
		$projects = new Projects();
		$id_winner = $projects->getWinner();
    	
    	// find the winner project
    	$project = Doctrine::getTable("Projects")->find($id_winner);
		
		// this project	will not contest anymore	        
		$project->allow_contest = 0;
		$project->save ();
		$project->refresh ();
    	
		// add to the winner list
		$winner = new Winners();
		$winner->day = new Doctrine_Expression("NOW()");							
		$winner->votes = $project->getVotes();
		$winner->funds = $project->funds;
		$winner->id_project = $project->id_project;
    	$winner->save();
    	$winner->refresh();
			
		// update balance		        
		$balance = new FundsBalance ();
		$balance->amount = -1*$winner->funds;
		$balance->type_trans = 2;
		$balance->id_user = $project->id_user;
		$balance->date_trans = $winner->day;
		$balance->save ();
		$balance->refresh ();

		// reset all votes	        
		$votes->resetAll();

		// reset all votes per user	        
		$users->resetAllVotes();

		// save resul in log file
		$title = $project->title;
    	$logger->info ( "election run: success winner project($id_winner:$title)" );
    }
    
    // the user vote for a project
    public function pickAction()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
    	// disabled the layout and view
		$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        // the vote 
		$id = $this->_getParam('id', 0);    	
		$project = Doctrine::getTable("Projects")->find($id);
		$user = Doctrine::getTable("Users")->find($this->getUserId());

		// if no project with that id then go to the vote screen
		if (!$project) {
			// redirect to vote screen
			$this->_redirector->gotoSimple("vote", "election");
			return;
		}      

		// if user voted go to the election screen
		if ($user->allow_vote == 0) {
			// redirect to election screen
			$this->_redirector->gotoSimple("donate", "donation");
			return;
		}

		// add to votes per user
		$vote = Doctrine::getTable("Votes")->findOneById_userAndvalid($this->getUserId(), 1);
		if ($vote) {
			$vote->day = new Doctrine_Expression("NOW()");							
			$vote->id_project = $id;
		} else {
			$vote = new Votes();
			$vote->day = new Doctrine_Expression("NOW()");							
			$vote->valid = 1;
			$vote->id_user = $this->getUserId();
			$vote->id_project = $id;
		}
    	$vote->save();
    	$vote->refresh();

		// user has voted 
		$user->voted = 1;
		$user->updateWithNoPassword();
		
        // open log file
		$writer = new Zend_Log_Writer_Stream ( ROOT_PATH.'/tmp/election.log' );
		$logger = new Zend_Log ( $writer );
		$username = $user->username; $title = $project->title;
		$logger->info ( "user vote: user:$username project:$id($title)" );
		
		// redirect to election screen
		$this->_redirector->gotoSimple("index", "election");
    }
    
}

